package com.msi.shortwave;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.osmdroid.bonuspack.location.GeocoderNominatim;
import org.osmdroid.bonuspack.overlays.ExtendedOverlayItem;
import org.osmdroid.bonuspack.overlays.Polygon;
import org.osmdroid.bonuspack.overlays.Polyline;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;





import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class mapsosm extends Fragment {
	 View v;
	 Location location = null;
	    ArrayList<OverlayItem> anotherOverlayItemArray = new ArrayList<OverlayItem>();
	    ArrayList<ExtendedOverlayItem> bubbleOverlayItemArray = new ArrayList<ExtendedOverlayItem>();
	
  
     public Bitmap textAsBitmap(String text, float textSize, int textColor) {
  	    Paint paint = new Paint();
  	    paint.setTextSize(textSize);
  	    paint.setColor(textColor);
  	   
  	    paint.setTextAlign(Paint.Align.LEFT);
  	
  	    int width = (int) (paint.measureText(text) + 0.5f); // round
  	    float baseline = (int) (-paint.ascent() + 0.5f); // ascent() is negative
  	    int height = (int) (baseline + paint.descent() + 0.5f);
  	    Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  	    Canvas canvas = new Canvas(image);
 	
  	    canvas.drawText(text, 0, baseline, paint);
  	    return image;
     }
	
   
   
	 public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {
		 
		 
		 View v = inflater.inflate(R.layout.mapsosm, null, false);
		 if (android.os.Build.VERSION.SDK_INT > 9) {

		 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		 }
		 MapView maposm = (MapView) v.findViewById(R.id.osmmap);
		 maposm.setBuiltInZoomControls(true);
		 maposm.setMultiTouchControls(true);
		 maposm.getController().setZoom(2);
		    float lat = 53.6f;
		    float lng = -3f;
		    GeoPoint gp = new GeoPoint((int)(lat * 1E6), (int)(lng * 1E6));
		    maposm.getController().setCenter(gp);
		    
			
			
		    
		    Bundle bund1 = getArguments();
		    ArrayList<Bundle> trans = (ArrayList) bund1.getSerializable("markers");
		    Boolean all = bund1.getBoolean("all");
		    Boolean offline = bund1.getBoolean("offline");
		   

		    for(Bundle transitem : trans){
		 	 Log.i("SW4",transitem.toString());
		 	   String longitude = transitem.getString("long");
		 		String latitude = transitem.getString("lat");
		 		String targetlat = transitem.getString("targetlat");
		 		String targetlong = transitem.getString("targetlong");
		 		String name = transitem.getString("name");
		 		String stationname = transitem.getString("stationname");
		 		
		 		String azi = transitem.getString("azi");
		 		String power = transitem.getString("power");
		 		Long type = transitem.getLong("type");
		 		String targets = transitem.getString("targets");
		 		String freq = transitem.getString("freq");
		 		
		 		if (type==1 && !offline){
		 			//Log.i("SW3","hi" + type.toString());
		 			GeocoderNominatim geocoder = new GeocoderNominatim(getActivity());
		 			try {
 			        	Log.i("SW4", "HERE2");

		 			    	//Log.i("SW3",targets.trim());
		 			        List<Address> addresses = geocoder.getFromLocationName(targets.trim().toLowerCase(), 1);
		 			        if (addresses.size() > 0) {
		 			        	targetlat = String.valueOf(addresses.get(0).getLatitude());
		 			        	targetlong = String.valueOf(addresses.get(0).getLongitude());
		 			        	
		 			        }
		 			    } catch (IOException e) {
		 			        e.printStackTrace();
		 		        	
		 			    }
		 			}
		 		
		 		if (type ==0 || (type ==1 && !offline)){

		 		if (longitude.contains("W")){
		 			longitude=longitude.replace("W", ".");
		 			longitude = "-" + longitude;
		 		}else{
		 			longitude = longitude.replace("E", ".");
		 		}
		 		
		 		if (latitude.contains("S")){
		 			latitude = latitude.replace("S", ".");
		 			latitude = "-" + latitude;
		 		}else{
		 			latitude = latitude.replace("N", ".");
		 		}
/*
		 		ExtendedOverlayItem bubbleitem = new ExtendedOverlayItem(
			            name, name, new GeoPoint(Double.parseDouble(latitude), Double.parseDouble(longitude)),getActivity());
		 		bubbleitem.setTitle(name);
		 		bubbleitem.setDescription("test");
		 		bubbleitem.setSubDescription("test2");
		 		bubbleOverlayItemArray.add(bubbleitem);
		 		*/
		 		if (name.length() > 1){
		 		Drawable drawfreq = new BitmapDrawable(getResources(),textAsBitmap(name, 20, Color.BLACK));
		 		OverlayItem oi = new OverlayItem(name, name, new GeoPoint(Double.parseDouble(latitude), Double.parseDouble(longitude)));
		 		oi.setMarker(drawfreq);
		 		anotherOverlayItemArray.add(oi);
		 		
		 		
		 		
		 		if (azi.length() > 1 && !azi.contains("ND") && !targetlat.equals("")  ){


		 			Location locationA = new Location("point A");

		 			locationA.setLatitude(Double.valueOf(latitude));
		 			locationA.setLongitude(Double.valueOf(longitude));

		 			Location locationB = new Location("point B");
		 			//Log.i("SW3",targetlat);
		 			locationB.setLatitude(Double.parseDouble(targetlat));
		 			locationB.setLongitude(Double.parseDouble(targetlong));

		 			float distance = locationA.distanceTo(locationB);
		 			
		 			
		 		
		 		
		 		double lat1 = Math.toRadians(Double.valueOf(latitude));
		 		double lon1 = Math.toRadians(Double.valueOf(longitude));
		 		if (power.length() < 1){
		 				power = "0";
		 		}
		 		
		 		if (power.contains(")")){
		 			power=power.replaceAll("[^0-9]", "");
		 		}
		 		
		 		if (Double.valueOf(freq.replace("Khz", "").trim()) < 2000){
		 			power = "0";
		 		}
		 		
		 		double d = (distance/1000)+((Double.valueOf(power)*10));
		 	
		 		
		 		
		 		Double brng = Math.toRadians(Double.valueOf(azi));
		 		Double lat2 = Math.asin( Math.sin(lat1)*Math.cos(d/6731) + 
		 		              Math.cos(lat1)*Math.sin(d/6731)*Math.cos(brng) );
		 		Double lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(d/6731)*Math.cos(lat1), 
		 		                     Math.cos(d/6731)-Math.sin(lat1)*Math.sin(lat2));
		 		Random randomGenerator = new Random();
		 		int randomInt = randomGenerator.nextInt(5);
		 		
		 		Drawable drawfreqstation = new BitmapDrawable(getResources(),textAsBitmap(stationname + " - "+freq, 20, Color.BLUE));
		 		OverlayItem oistation = new OverlayItem(name, name, new GeoPoint(Math.toDegrees(lat2)+randomInt, Math.toDegrees(lon2)+randomInt));
		 		oistation.setMarker(drawfreqstation);
		 		anotherOverlayItemArray.add(oistation);
		 		double modilon1 =0;
		 		double modilon2= 0;
		 		double modilat1=0;
		 		double modilat2=0;;
		 	
		 		if (Double.valueOf(azi) > -1 & Double.valueOf(azi) < 46){
		 			modilon1 = 20;
		 			modilon2 = -20;
		 		}else if (Double.valueOf(azi) > 45 & Double.valueOf(azi) < 135){
		 			modilat1 = 20;
		 			modilat2 = -20;
		 		}else if (Double.valueOf(azi) > 134 & Double.valueOf(azi) < 225){
		 			modilon1 = 20;
		 			modilon2 = -20;
		 		}else if (Double.valueOf(azi) > 224 & Double.valueOf(azi) < 315 ){
		 			modilat1 = 20;
		 			modilat2 = -20;
		 		}else if (Double.valueOf(azi) > 314 & Double.valueOf(azi) < 361){
		 			modilon1 = 20;
		 			modilon2 = -20;
		 		}
		 		
		 		//markers.add(target); 
		 		int colour = 0x3FFF0000;
		 		/*
		 		if (Double.valueOf(power) > -1 & Double.valueOf(power) < 101){
		 			colour = 0x3F66FF33;
		 		}else if (Double.valueOf(power) < 251 & Double.valueOf(power) > 101 ){
		 			colour = 0x3FFFFF00;
		 		}else if (Double.valueOf(power) < 501 & Double.valueOf(power) > 250 ){
		 			colour = 0x3FFF0000; }
		 		else{ 
		 			colour = 0x3FFF0000;
		 		}
		 		*/
		 			/*
		 		 Polygon line=
		 			      new PolygonOptions().add(new LatLng(Double.parseDouble(latitude),
		 			    		  Double.parseDouble(longitude)),
		 			    		  new LatLng(Math.toDegrees(lat2)+modilat1, Math.toDegrees(lon2)+modilon1),
		 			    		  new LatLng(Math.toDegrees(lat2)+modilat2, Math.toDegrees(lon2)+modilon2))
		 			                           .fillColor(colour).strokeWidth(0).geodesic(true);

		 			  map.addPolygon(line);
*/
		 		
			    ArrayList<GeoPoint> polylist = new ArrayList<GeoPoint>();
			    polylist.add(new GeoPoint(Double.parseDouble(latitude),Double.parseDouble(longitude)));
			    polylist.add(new GeoPoint(Math.toDegrees(lat2)+modilat1, Math.toDegrees(lon2)+modilon1));
			    polylist.add(new GeoPoint(Math.toDegrees(lat2)+modilat2, Math.toDegrees(lon2)+modilon2));
			    polylist.add(new GeoPoint(Double.parseDouble(latitude),Double.parseDouble(longitude)));

			    
		 		Polygon poly = new Polygon(getActivity());
		 		poly.setPoints(polylist);
		 		poly.setFillColor(colour);
		 		poly.setStrokeWidth(0);
		 		poly.setStrokeColor(colour);
                List<Overlay> mapOverlays = maposm.getOverlays();

                mapOverlays.add(poly);
		 		
		 			  
		 		}else{
		 			//Log.i("SW4","AZ" + azi.toString());
		 			//if (azi.length() > 1 && azi.contains("ND")){
		 			//	OverlayItem oistation = new OverlayItem(name, name, new GeoPoint(Double.parseDouble(targetlat)+randomInt, Double.parseDouble(targetlong)+randomInt));
				 	//	oistation.
		 			//	Log.i("SW4","ND");
		 			//}else{
		 				
		 			if (!targetlat.equals("")){
		 			Random randomGenerator = new Random();
		 			  int randomInt = randomGenerator.nextInt(5);
		 			
		 		
		 			 Drawable drawfreqstation = new BitmapDrawable(getResources(),textAsBitmap(stationname + " - "+freq, 20, Color.BLUE));
				 		OverlayItem oistation = new OverlayItem(name, name, new GeoPoint(Double.parseDouble(targetlat)+randomInt, Double.parseDouble(targetlong)+randomInt));
				 		oistation.setMarker(drawfreqstation);
				 		anotherOverlayItemArray.add(oistation);
				 		
				 		 ArrayList<GeoPoint> polyline = new ArrayList<GeoPoint>();
				 			polyline.add(new GeoPoint(Double.parseDouble(latitude),Double.parseDouble(longitude)));
				 			polyline.add(new GeoPoint(Double.parseDouble(targetlat), Double.parseDouble(targetlong)));
						    

				 			Polyline polyl = new Polyline(getActivity());
				 			polyl.setPoints(polyline);				 			
				 			polyl.setWidth(5);
				 			polyl.setColor(Color.RED);
			                List<Overlay> mapOverlays = maposm.getOverlays();
			                mapOverlays.add(polyl);
		 			}

		 			}
		 			
		 		}
		 		
		 		
		 		
		 					
		 		
		 		}
		 	   
		 	 }
		    
		  
		    LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
		    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		     
		    if( location != null ) {
		    	
		    	
		        GeoPoint currentLocation = new GeoPoint(location.getLatitude(), location.getLongitude());
		 		Drawable drawfreq = new BitmapDrawable(getResources(),textAsBitmap("Your Location", 20, Color.BLACK));
		 		OverlayItem oi = new OverlayItem("home", "home", currentLocation);
		 		oi.setMarker(drawfreq);
		 		anotherOverlayItemArray.add(oi);
		        
		    }
		   

		   
		    
		    
		    ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay  = new ItemizedIconOverlay<OverlayItem>(
			          getActivity(), anotherOverlayItemArray, null);
		    /*
			ItemizedOverlayWithBubble <ExtendedOverlayItem> bubbleItemizediconArray  = new ItemizedOverlayWithBubble <ExtendedOverlayItem>(
			          getActivity(), bubbleOverlayItemArray, null);
		    		
				map.getOverlays().add(bubbleItemizediconArray);
*/
		    maposm.getOverlays().add(anotherItemizedIconOverlay);
		    maposm.setTileSource(TileSourceFactory.MAPNIK);
		    if (offline){
				
				maposm.setMaxZoomLevel(4);

		    }else{
		    }
    
   return v;
}



}


